<?php
/*
PLUGIN NAME: Make It Mobile
PLUGIN URI: http://wp-plugin-dev.googlecode.com/
DESCRIPTION: Make It Mobile produces valid XHTML Mobile Profile 1.2 after detecting a mobile user agent, e.g., a mobile phone, Blackberry,  Palm, so your blog remains accessible, looks great, and loads fast. Make It Mobile also allows you to display Google Adsense Mobile to mobile user agents. For WordPress 2.5.x.
AUTHOR: Scott Allan Wallick
AUTHOR URI: http://scottwallick.com/
VERSION: 0.2.1
*/

$version = null;
$version = '0.2.1';

/*
MAKE IT MOBILE
by SCOTT ALLAN WALLICK, http://scottwallick.com/
from PLAINTXT.ORG, http://www.plaintxt.org/

MAKE IT MOBILE is free software: you can redistribute it and/or
modify it under the terms of the GNU General Public License as
published by the Free Software Foundation, either version 3 of
the License, or (at your option) any later version.

MAKE IT MOBILE is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for details.

You should have received a copy of the GNU General Public License
along with MAKE IT MOBILE. If not, see www.gnu.org/licenses/.
*/

function mim_check_mobile() {
	if ( !isset($_SERVER["HTTP_USER_AGENT"]) || ( isset($_COOKIE['mim_mobile']) && $_COOKIE['mim_mobile'] == 'false' ) )
		return false;
	if ( preg_match( "/iphone/i", $_SERVER["HTTP_USER_AGENT"] ) )
		return false;
	$mobile_browser = 0;
	if ( isset($_SERVER["HTTP_X_WAP_PROFILE"]) )
		$mobile_browser++;
	if ( preg_match( "/wap\.|\.wap/i", $_SERVER["HTTP_ACCEPT"] ) )
		$mobile_browser++;
	if ( isset($_SERVER["HTTP_USER_AGENT"]) ) {
		$mobile_agents = array(
			"midp","j2me","avant","docomo","novarra","palmos","palmsource",
			"240x320","opwv","chtml","pda","windows\ ce","mmp\/","blackberry",
			"mib\/","symbian","wireless","nokia","hand","mobi","phone","cdm",
			"up\.b","audio","SIE\-","SEC\-","samsung","HTC","mot\-","mitsu",
			"sagem","sony","alcatel","lg","eric","vx","NEC","philips","mmm",
			"xx","panasonic","sharp","wap","sch","rover","pocket","benq",
			"java","pt","pg","vox","amoi","bird","compal","kg","voda","sany",
			"kdd","dbt","sendo","sgh","gradi","jb","\d\d\di","moto"
		);
		foreach ( $mobile_agents as $mobile_agent ) {
			if ( preg_match( "/".$mobile_agent."/i", $_SERVER["HTTP_USER_AGENT"] ) )
				$mobile_browser++;
		}
	}
	if ( $mobile_browser>0 ) {
		return true;
	} else {
		return false;
	}
}

function mim_mobile_redirect() {
	$redirect = true;
	$pages_to_exclude = array(
		'wp-admin',
		'wp-mobile.php',
		'wp-comments-post.php',
		'wp-mail.php',
		'wp-login.php'
	);
	foreach ( $pages_to_exclude as $exclude ) {
		if ( strstr( strtolower($_SERVER['REQUEST_URI']), $exclude ) ) {
			$redirect = false;
		}
	}
	return $redirect;
}

function mim_theme_root($directory) {
	return ABSPATH . 'wp-content/plugins/mim';
}

function mim_theme_root_uri($directory) {
	return get_bloginfo('wpurl') . '/wp-content/plugins/mim';
}

function mim_template($theme) {
	return 'm';
}

function mim_standard_content($content) {
	return $content . printf( __( '<div class="mobi-link"><a href="%s" title="View mobile-optimized version">Mobile version</a> | Viewing standard version</div>', 'mim' ), get_bloginfo('wpurl') . '/wp-admin/options-general.php?mim_action=use_mobile' );
}

function mim_standard_header() {
	printf( __( "\t" . '<link rel="alternate" media="handheld" href="%s" />' . "\n", 'mim' ), get_bloginfo('wpurl') . '/wp-admin/options-general.php?mim_action=use_mobile' );
}

if ( isset($_GET['mim_action']) ) {
	$url = parse_url( get_bloginfo('url') );
	$domain = $url['host'];
	if ( !empty($url['path']) ) {
		$path = $url['path'];
	} else {
		$path = '/';
	}
	$redirect = false;
	switch ( $_GET['mim_action'] ) {
		case 'use_standard' :
			setcookie(
				'mim_mobile',
				'false',
				time() + 86400,
				$path,
				$domain
			);
			$redirect = true;
			break;
		case 'use_mobile':
			setcookie(
				'mim_mobile', 
				'true',
				time() + 86400,
				$path,
				$domain
			);
			$redirect = true;
			break;
	}
	if ($redirect) {
		if ( !empty($_SERVER['HTTP_REFERER']) ) {
			$go = $_SERVER['HTTP_REFERER'];
		} else {
			$go = get_bloginfo('url');
		}
		header('Location: ' . $go);
		die();
	}
}

function mim_mobile_headers() {
	header('Vary: Accept');
	$charset = get_bloginfo('charset');
	$xhtml_v = get_option('mim_mobile_xhtml');
	if ( strpos( strtolower($_SERVER['HTTP_ACCEPT']), 'application/vnd.wap.xhtml+xml' ) ) {
		$mime_type = 'application/xhtml+xml';
		if ( $xhtml_v == 1 ) {
			$doctype = '<!DOCTYPE html PUBLIC "-//WAPFORUM//DTD XHTML Mobile 1.0//EN" "http://www.wapforum.org/DTD/xhtml-mobile10.dtd">';
		} elseif ( $xhtml_v == 2 ) {
			$doctype = '<!DOCTYPE html PUBLIC "-//WAPFORUM//DTD XHTML Mobile 1.1//EN" "http://www.openmobilealliance.org/tech/DTD/xhtml-mobile11.dtd">';
		} elseif ( $xhtml_v == 3 ) {
			$doctype = '<!DOCTYPE html PUBLIC "-//WAPFORUM//DTD XHTML Mobile 1.2//EN" "http://www.openmobilealliance.org/tech/DTD/xhtml-mobile12.dtd">';
		} elseif ( $xhtml_v == 4 ) {
			$doctype = '<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML Basic 1.0//EN" "http://www.w3.org/TR/xhtml-basic/xhtml-basic10.dtd">';
		} elseif ( $xhtml_v == 5 ) {
			$doctype = '<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML Basic 1.1//EN" "http://www.w3.org/TR/xhtml-basic/xhtml-basic11.dtd">';
		} else {
			$doctype = '<!DOCTYPE html PUBLIC "-//WAPFORUM//DTD XHTML Mobile 1.2//EN" "http://www.openmobilealliance.org/tech/DTD/xhtml-mobile12.dtd">';
		}
	} elseif ( strpos( strtolower($_SERVER['HTTP_ACCEPT']), 'text/vnd.wap.wml' ) ) {
		$mime_type = 'text/html';
		if ( $xhtml_v == 1 ) {
			$doctype = '<!DOCTYPE html PUBLIC "-//WAPFORUM//DTD XHTML Mobile 1.0//EN" "http://www.wapforum.org/DTD/xhtml-mobile10.dtd">';
		} elseif ( $xhtml_v == 2 ) {
			$doctype = '<!DOCTYPE html PUBLIC "-//WAPFORUM//DTD XHTML Mobile 1.1//EN" "http://www.openmobilealliance.org/tech/DTD/xhtml-mobile11.dtd">';
		} elseif ( $xhtml_v == 3 ) {
			$doctype = '<!DOCTYPE html PUBLIC "-//WAPFORUM//DTD XHTML Mobile 1.2//EN" "http://www.openmobilealliance.org/tech/DTD/xhtml-mobile12.dtd">';
		} elseif ( $xhtml_v == 4 ) {
			$doctype = '<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML Basic 1.0//EN" "http://www.w3.org/TR/xhtml-basic/xhtml-basic10.dtd">';
		} elseif ( $xhtml_v == 5 ) {
			$doctype = '<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML Basic 1.1//EN" "http://www.w3.org/TR/xhtml-basic/xhtml-basic11.dtd">';
		} else {
			$doctype = '<!DOCTYPE html PUBLIC "-//WAPFORUM//DTD XHTML Mobile 1.2//EN" "http://www.openmobilealliance.org/tech/DTD/xhtml-mobile12.dtd">';
		}
	} elseif ( strpos( strtolower($_SERVER['HTTP_ACCEPT']), 'application/xhtml+xml' ) ) {
		$mime_type = 'application/xhtml+xml';
		$doctype = '<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML Basic 1.0//EN" "http://www.w3.org/TR/xhtml-basic/xhtml-basic10.dtd">';
	} else {
		$mime_type = 'text/html';
		$doctype = '<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">';
	}
	header("Cache-Control: Public");
	header("Pragma: Public");
	header("Expires: " . gmdate( "D, d M Y H:i:s", strtotime('+12 hours')  ) . " GMT");
	header("Content-Type: $mime_type; charset=$charset");
	print "<?xml version=\"1.0\" encoding=\"$charset\"?>\n$doctype\n<html xmlns=\"http://www.w3.org/1999/xhtml\">\n<head>\n<meta http-equiv=\"Content-Type\" content=\"$mime_type; charset=$charset\" />\n";
}

function mim_mobile_adsense() {
	$format           =  attribute_escape(get_option('mim_adsensemob_io'));
	if ( $format != 'off' ) {
		$background   =  attribute_escape(get_option('mim_adsensemob_bg'));
		$border       =  attribute_escape(get_option('mim_adsensemob_border'));
		$channel      =  attribute_escape(get_option('mim_adsensemob_channel'));
		$charset      =  get_bloginfo('charset');
		$link         =  attribute_escape(get_option('mim_adsensemob_link'));
		$pub_client   =  attribute_escape(get_option('mim_adsensemob_pub'));
		$text         =  attribute_escape(get_option('mim_adsensemob_text'));
		$url          =  attribute_escape(get_option('mim_adsensemob_url'));
		function google_set_screen_res() {
			$screen_res = $_SERVER['HTTP_UA_PIXELS'];
			$delimiter = 'x';
			if ( $screen_res == '' ) {
				$screen_res = $_SERVER['HTTP_X_UP_DEVCAP_SCREENPIXELS'];
				$delimiter = ',';
			}
			$res_array = explode( $delimiter, $screen_res );
			if ( sizeof($res_array) == 2 ) {
				$GLOBALS['google']['u_w'] = $res_array[0];
				$GLOBALS['google']['u_h'] = $res_array[1];
			}
		}
		$GLOBALS['google']['ad_type']       =  'text';
		$GLOBALS['google']['channel']       =  "$channel";
		$GLOBALS['google']['client']        =  "$pub_client";
		$GLOBALS['google']['color_border']  =  "$border";
		$GLOBALS['google']['color_bg']      =  "$background";
		$GLOBALS['google']['color_link']    =  "$link";
		$GLOBALS['google']['color_text']    =  "$text";
		$GLOBALS['google']['color_url']     =  "$url";
		$GLOBALS['google']['format']        =  "$format";
		$GLOBALS['google']['https']         =  $_SERVER['HTTPS'];
		$GLOBALS['google']['host']          =  $_SERVER['HTTP_HOST'];
		$GLOBALS['google']['ip']            =  $_SERVER['REMOTE_ADDR'];
		$GLOBALS['google']['markup']        =  'xhtml';
		$GLOBALS['google']['oe']            =  "$charset";
		$GLOBALS['google']['output']        =  'xhtml';
		$GLOBALS['google']['ref']           =  $_SERVER['HTTP_REFERER'];
		$GLOBALS['google']['url']           =  $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI'];
		$GLOBALS['google']['useragent']     =  $_SERVER['HTTP_USER_AGENT'];
		$google_dt                          =  time();
		google_set_screen_res();
		function google_append_url( &$url, $param, $value ) {
			$url .= '&' . $param . '=' . urlencode($value);
		}
		function google_append_globals( &$url, $param ) {
			google_append_url( $url, $param, $GLOBALS['google'][$param] );
		}
		function google_append_color(&$url, $param) {
			global $google_dt;
			$color_array = split( ',', $GLOBALS['google'][$param] );
			google_append_url( $url, $param, $color_array[$google_dt % sizeof($color_array)] );
		}
		function google_get_ad_url() {
			$google_ad_url = 'http://pagead2.googlesyndication.com/pagead/ads?';
			$google_scheme = ( $GLOBALS['google']['https'] == 'on' ) ? 'https://' : 'http://';
			foreach ( $GLOBALS['google'] as $param => $value ) {
				if ( $param == 'client' ) {
					google_append_url( $google_ad_url, $param, 'ca-mb-' . $GLOBALS['google'][$param] );
				} elseif ( strpos($param, 'color_') === 0 ) {
					google_append_color( $google_ad_url, $param );
				} elseif ( (strpos( $param, 'host' ) === 0 ) || (strpos( $param, 'url' ) === 0) ) {
					google_append_url( $google_ad_url, $param, $google_scheme . $GLOBALS['google'][$param] );
				} else {
					google_append_globals( $google_ad_url, $param );
				}
			}
			google_append_url( $google_ad_url, 'dt', round( 1000 * array_sum(explode( ' ', microtime() )) ) );
			return $google_ad_url;
		}
		$google_ad_handle = @fopen( google_get_ad_url(), 'r' );
		if ($google_ad_handle) {
			while ( !feof($google_ad_handle) ) {
				echo '<div class="ad">' . fread( $google_ad_handle, 8192 ) . "</div>\n";
			}
			fclose($google_ad_handle);
		}
	}
}

function mim_activation() {
	$admin_info  =  get_userdata(1);
	$new_option  =  date('Y') . ' ' . $admin_info->display_name;
	add_option( 'mim_adsensemob_bg', 'EEEEEE', '', 'yes' );
	add_option( 'mim_adsensemob_border', '555555', '', 'yes' );
	add_option( 'mim_adsensemob_channel', '', '', 'yes' );
	add_option( 'mim_adsensemob_io', 0, '', 'yes' );
	add_option( 'mim_adsensemob_link', '0000CC', '', 'yes' );
	add_option( 'mim_adsensemob_pub', 'pub-3766589781871613', '', 'yes' );
	add_option( 'mim_adsensemob_text', '000000', '', 'yes' );
	add_option( 'mim_adsensemob_url', '008000', '', 'yes' );
	add_option( 'mim_color_b', 'FF0000', '', 'yes' );
	add_option( 'mim_color_d', '0000FF', '', 'yes' );
	add_option( 'mim_color_l', 'FFFFFF', '', 'yes' );
	add_option( 'mim_comment_avatar_io', 'off', '', 'yes' );
	add_option( 'mim_comment_avatar_sz', 16, '', 'yes' );
	add_option( 'mim_comment_mobilizer', 'http://www.google.com/gwt/n?u=', '', 'yes' );
	add_option( 'mim_footer_text', __( "&copy; $new_option", "mim" ), '', 'yes' );
	add_option( 'mim_gray_d', '666666', '', 'yes' );
	add_option( 'mim_gray_l', 'EEEEEE', '', 'yes' );
	add_option( 'mim_gray_m', '999999', '', 'yes' );
	add_option( 'mim_mobile_xhtml', 3, '', 'yes' );
	add_option( 'mim_page_list_exclude', '', '', 'yes' );
	add_option( 'mim_page_list_sorting', 'menu_order', '', 'yes' );
	add_option( 'mim_page_list_title', __( 'Pages', 'mim' ), '', 'yes' );
	add_option( 'mim_quick_link_title', __( 'Quick links', 'mim' ), '', 'yes' );
	add_option( 'mim_search_form_button', __( 'Find', 'mim' ), '', 'yes' );
	add_option( 'mim_search_form_title', __( 'Search', 'mim' ), '', 'yes' );
	add_option( 'mim_updated_today', __( 'New today:', 'mim' ), '', 'yes' );
}

function mim_deactivation() {
	delete_option('mim_adsensemob_bg');
	delete_option('mim_adsensemob_border');
	delete_option('mim_adsensemob_channel');
	delete_option('mim_adsensemob_format');
	delete_option('mim_adsensemob_io');
	delete_option('mim_adsensemob_link');
	delete_option('mim_adsensemob_pub');
	delete_option('mim_adsensemob_text');
	delete_option('mim_adsensemob_url');
	delete_option('mim_color_b');
	delete_option('mim_color_d');
	delete_option('mim_color_l');
	delete_option('mim_color_m');
	delete_option('mim_comment_avatar_io');
	delete_option('mim_comment_avatar_sz');
	delete_option('mim_comment_mobilizer');
	delete_option('mim_footer_text');
	delete_option('mim_gray_d');
	delete_option('mim_gray_l');
	delete_option('mim_gray_m');
	delete_option('mim_mobile_xhtml');
	delete_option('mim_page_list_exclude');
	delete_option('mim_page_list_sorting');
	delete_option('mim_page_list_title');
	delete_option('mim_quick_link_title');
	delete_option('mim_search_form_button');
	delete_option('mim_search_form_title');
	delete_option('mim_updated_today');
	delete_option('mim_version');
}

function mim_zap_whitespace($content) {
	return str_replace( array( "\r", "\n", "\t" ), '', $content );
}

function mim_initialize() {
	if ( function_exists('add_options_page') ) {
		add_options_page( __( 'Make It Mobile', 'scf' ), __( 'Mobile', 'scf' ), 'manage_options', 'mim/mim-menu.php', '' );
	}
}

function mim_admin_head() {
?>
<style type="text/css">
/*<![CDATA[*/
div.wrap table span.colorPreview { background: #FFF; border: 1px solid #000; display: block; float: left; height: 20px; width: 35px; margin:2px 5px 0 0;  }
/*]]>*/
</style>
<?php
}

if ( mim_mobile_redirect() && mim_check_mobile() || isset($_COOKIE['mim_mobile']) && $_COOKIE['mim_mobile'] == 'true' ) {
	add_filter( 'theme_root', 'mim_theme_root' );
	add_filter( 'theme_root_uri', 'mim_theme_root_uri' );
	add_action( 'template', 'mim_template' );
	add_action( 'option_template', 'mim_template' );
	add_action( 'option_stylesheet', 'mim_template' );
	add_filter( 'the_content', 'mim_zap_whitespace', 99 );
	add_filter( 'the_content_rss', 'mim_zap_whitespace', 99 );
	add_filter( 'wp_list_categories', 'mim_zap_whitespace', 99 );
	add_filter( 'wp_list_bookmarks', 'mim_zap_whitespace', 99 );

} elseif ( isset($_COOKIE['mim_mobile']) && $_COOKIE['mim_mobile'] == 'false' ) {
	add_action( 'the_content', 'mim_standard_content' );
} else {
	add_action( 'wp_head', 'mim_standard_header' );
}

register_activation_hook( __FILE__, 'mim_activation' );
register_deactivation_hook( __FILE__, 'mim_deactivation' );

add_action( 'admin_menu', 'mim_initialize' );
add_action( 'admin_head-mim/mim-menu.php', 'mim_admin_head' );
?>